#include "stdafx.h"
#include "ConnectionHandler.h"

ConnectionHandler::ConnectionHandler()
{
}

ConnectionHandler::~ConnectionHandler()
{
}

bool ConnectionHandler::connect(IpModel^ ipModel)
{
	try{
		String^ ip = ipModel->getIpAddress();
		int len = ip->Length;
	
		char arrayChar[100];

		for(int i = 0; i < len; i++)
		{
			arrayChar[i] = ip[i];			
		}

		arrayChar[len]=0;

		gTelnet = TELNET::createTelnet(arrayChar, (unsigned)ipModel->getPort());

	} catch (...){
		//MessageBox::Show("Unable to open connection","Warning",MessageBoxButtons::OK,MessageBoxIcon::Warning);
		return false;
	}
	if (gTelnet != NULL){
		if(gTelnet->haveConnection() && !gTelnet->isServer())
		{
			System::Diagnostics::Debug::WriteLine("Conectado como cliente.");
			//MessageBox::Show(gTelnet->isServer()+"");
			getMessages();
			sendMessage("\r\n");
			getMessages();

			/*
			sendMessage("enable\r\n");
			getMessages();


			sendMessage(ipModel->getPassword()+"\r\n");
			getMessages();
			sendMessage("config\r\n");
			sendMessage("\r\n");
			getMessages();
			sendMessage("?");
			getMessages();
			*/

			return true;
		}
		else
		{
			System::Diagnostics::Debug::WriteLine("Conectado como servidor.");
			//MessageBox::Show(gTelnet->isServer()+"");

			//TELNET::releaseTelnet(gTelnet);
			return false;
		}
	} else {
		//MessageBox::Show("Unable to open connection","Warning",MessageBoxButtons::OK,MessageBoxIcon::Warning);
		return false;
	}
}

bool ConnectionHandler::sendMessage(String^ message)
{
	//System::Diagnostics::Debug::WriteLine("Envia mensagem:" + message);
	int len = message->Length;
	
	char arrayChar[100];

	for(int i = 0; i < len; i++)
	{
		//System::Diagnostics::Debug::WriteLine(message[i]);
		arrayChar[i] = message[i];			
	}

	arrayChar[len]=0;

	unsigned int client = 0;

	gTelnet->sendMessage(client, arrayChar);

	return true;
}

List<const char*> ConnectionHandler::getMessages()
{
	delay();
	//System::Diagnostics::Debug::WriteLine("Acabou o delay, lendo mensagens");

	const char* arrayChar;

	unsigned int client = 0;

	bool messageReceived = false;
	
	List<const char*> lista;

	do
	{
		messageReceived = false;
		arrayChar = gTelnet->receiveMessage(client);
		
		if(arrayChar != NULL)
		{
			lista.insert(arrayChar);
			System::Diagnostics::Debug::WriteLine(gcnew String(arrayChar));
			messageReceived = true;
			delay();
		}
	}while(messageReceived);

	return lista;
}

bool ConnectionHandler::needPassword(String^ texto)
{
	unsigned int client = 0;
	
	return true;
}

